﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.XPath;
using System.Text.RegularExpressions;
namespace BitPortal.Utils
{
    public class VideoInfo
    {
        public string Title { set; get; }
        public string Description { set; get; }
        public string Keyword { set; get; }
        public int Duration { set; get; }
        public string Id { set; get; }
        public string Thumbnail { set; get; }
        public string Url { set; get; }
    }
    public static class VideoUtils
    {
        public static VideoInfo GetYoutubeVideo(string videoID)
        {
            VideoInfo video = new VideoInfo();
            //check if input string is url
            Regex re = new Regex("(v)(=|/)([a-zA-Z0-9]{11})");
            Match m = re.Match(videoID);
            if (m.Success)
            {
                return GetYoutubeVideo(m.Groups[3].Value);
            }
            XPathDocument xmlInfo = new XPathDocument("http://gdata.youtube.com/feeds/api/videos/" + videoID);
            XPathNavigator navi = xmlInfo.CreateNavigator();
            //Add namespace
            XmlNamespaceManager nsMgr = new XmlNamespaceManager(navi.NameTable);
            nsMgr.AddNamespace("en", "http://www.w3.org/2005/Atom");
            nsMgr.AddNamespace("app", "http://purl.org/atom/app#");
            nsMgr.AddNamespace("media", "http://search.yahoo.com/mrss/");
            nsMgr.AddNamespace("gd", "http://schemas.google.com/g/2005");
            nsMgr.AddNamespace("yt", "http://gdata.youtube.com/schemas/2007");
            //Load data to Video object
            video.Id = videoID;
            video.Title = navi.SelectSingleNode("en:entry/media:group/media:title", nsMgr).Value;
            video.Description = navi.SelectSingleNode("en:entry/media:group/media:description", nsMgr).Value;
            video.Keyword = navi.SelectSingleNode("en:entry/media:group/media:keywords", nsMgr).Value;
            video.Duration = Convert.ToInt32(navi.SelectSingleNode("en:entry/media:group/yt:duration/@seconds", nsMgr).Value);
            video.Thumbnail = navi.SelectSingleNode("en:entry/media:group/media:thumbnail/@url", nsMgr).Value;
            video.Url = "http://www.youtube.com/v/" + videoID;
            return video;
        }
    }
}
